package com.doradance.account.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by Administrator on 2018/2/28.
 */

@SuppressLint("AppCompatCustomView")
public class CustomView extends ImageView {

    private static final String TAG = null;
    private Paint mPaint;
    private Bitmap bitmap;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setDither(true);
        mPaint.setColor(0xff0000ff);
        // OverScroller
    }

    private void drawBitmap(Bitmap src) {
        //关闭硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE, null);

        bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas();

        c.setBitmap(bitmap);

        // Dst 圆矩形
        c.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()), 20, 20,
                mPaint);

        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // src
        c.drawBitmap(src, 0, 0, mPaint);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        // TODO Auto-generated method stub
        super.onSizeChanged(w, h, oldw, oldh);

        BitmapDrawable bd = (BitmapDrawable) getDrawable();
        Bitmap mBitmap = bd.getBitmap();
        float rate = Math.max(getWidth() * 1.0f / mBitmap.getWidth(),
                getWidth() * 1.0f / mBitmap.getHeight());
        // mBitmap.setWidth((int) (rate*mBitmap.getWidth())); 不能直接设置
        // mBitmap.setHeight((int) (rate*mBitmap.getHeight()));
        // 缩小图片
        mBitmap = Bitmap.createScaledBitmap(mBitmap,
                (int) (rate * mBitmap.getWidth()),
                (int) (rate * mBitmap.getHeight()), true);

        drawBitmap(mBitmap);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, null);

    }
}
